import { z } from 'zod'
import { generateToken } from '@/utils'
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'

export default function register(server: McpServer) {
  server.registerTool(
    'GetCompanyDetail',
    {
      title: '查询企业工商信息',
      description:
        '实时查询企业工商信息（含工商照面信息），返回企业名称、企业类型、注册资本、统一社会信用代码、经营范围、营业期限、上市状态等信息。',
      inputSchema: {
        keyword: z
          .string()
          .describe('搜索关键词（支持统一社会信用代码、企业名称，对于社会组织、中国香港企业，仅支持搜索企业名称）'),
      },
    },
    async ({ keyword }) => {
      const { success, data, message } = await getCompanyDetail(keyword)
      return {
        content: [
          {
            type: 'text',
            text: success ? JSON.stringify(data) : message!,
          },
        ],
      }
    },
  )
}

export async function getCompanyDetail(keyword: string) {
  const key = 'xxx'
  const secretKey = 'xxx'
  const { token, timespan } = generateToken(key, secretKey)
  const url = new URL('https://api.qichacha.com/ECIV4/GetBasicDetailsByName')
  url.searchParams.append('key', key)
  url.searchParams.append('keyword', keyword)
  const headers = {
    Token: token,
    Timespan: timespan,
  }
  const response = await fetch(url.href, {
    method: 'GET',
    headers,
  })
  const data: any = await response.json()
  if (data.Status !== '200') {
    return {
      success: false,
      message: '未找到该企业',
    }
  }
  return {
    success: true,
    data: data.Result,
  }
}
